const sql = require('../sql/sqlConfig');
const express = require('express');
let router = express.Router();
const pagination = require('../util/page');

//增分销商的等级
router.post('/rule/add', function (req, res) {
    let this_level = req.body.level;//等级
    let this_target = req.body.target;//订单量
    let this_proportion = req.body.proportion;//抽成
    //查等级是否重复
    let getLevelSql = "select id from level_setting where level=" + this_level;
    sql.query(getLevelSql, function (err, rows) {
        if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
        if (rows[0]) return res.send({errCode: 9, message: '不可设置重复等级!'});
        //判断上一级的情况
        if(this_level==1){
            if(this_target!=0) return res.send({errCode: 9, message: '一级分销商对订单量没有要求，故只能设置为0!'});
            fina();
            return false
        }
        SuperiorCheck();
    });
    //查数据是否小于上一级
    function SuperiorCheck() {
        //查上一级的订单量和佣金百分比
        let lastSql = "select * from level_setting where level=" + (this_level - 1);
        sql.query(lastSql, function (err, rows) {
            if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
            if(!rows[0]) return res.send({errCode: 9, message: '不可跨级设置分销商等级!'});
            //上一级的值
            let last_order_num = rows[0].order_num;
            let last_proportion = rows[0].proportion;
            if (this_target <= last_order_num) return res.send({errCode: 9, message: '设置的订单量必须大于下级！'});
            if(parseInt(this_proportion)<=parseInt(last_proportion)) return res.send({errCode: 9, message: '设置的抽成比例必须大于下级！'});
            // 查抽成是否超过100%了，超过返回提示
            let countSql = "select sum(-(-`proportion`)) as count from `level_setting`";
            sql.query(countSql, function (err, rows) {
                if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
                let count = 100 - rows[0].count;//商家利益
                if (parseInt(this_proportion) > count) return res.send({errCode: 9, message: '佣金总抽成超过100%，商家要亏本了！'});
                fina();
            })
        })
    }
    //插入数据
    function fina(){
        let insertSql = "insert into level_setting(level,order_num,proportion) values('" + this_level + "','" + this_target + "','" + this_proportion+ "')";
        sql.query(insertSql, function (err, rows) {
            if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
            return res.send({errCode:0,message:'新增分销商等级成功!'});
        })
    }
});

//改分销商的等级
router.post('/rule/alter', function (req, res) {
    let id = req.body.id;
    let this_level = req.body.level;//等级
    let this_target = req.body.target;//订单量
    let this_proportion = req.body.proportion;//抽成
    let getLevelSql = "select * from level_setting where id=" + id;
    let oldData = {};
    sql.query(getLevelSql, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        if(!rows[0]) return res.send({errCode:9,message:'没有该条记录'});
        oldData = rows[0];
        if(this_level!=oldData.level) return res.send({errCode:9,message:'分销商的level不能改!'});
        if(this_level==1 && this_target!=0) return res.send({errCode:9,message:'一级分销商对订单量没有要求，故只能设置为0!'});
        if(this_level==1){
            let nextSql = "select * from level_setting where level=" + (this_level + 1);
            sql.query(nextSql, function (err, rows) {
                if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
                if(rows[0]){
                    if (this_target >= rows[0].order_num) return res.send({errCode: 9, message: '设置的订单量必须小于上级！'});
                    if (parseInt(this_proportion) >= parseInt(rows[0].proportion)) return res.send({errCode: 9, message: '设置的抽成比例必须小于上级！'});
                }
                let countSql = "select sum(-(-`proportion`)) as count from `level_setting`";
                sql.query(countSql, function (err, rows) {
                    if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
                    let count = 100-(rows[0].count-parseInt(oldData.proportion));
                    if (parseInt(this_proportion) > count) return res.send({errCode: 9, message: '佣金总抽成超过100%，商家要亏本了！'});
                    //执行修改
                    fina(1)
                });
            })
        }else if(this_level>1){
            SuperiorCheck()
        }
    });
    function SuperiorCheck() {
        //查上一级的订单量和佣金百分比
        let lastSql = "select * from level_setting where level=" + (this_level - 1);
        sql.query(lastSql, function (err, rows) {
            if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
            //上一级的值
            let last_order_num = rows[0].order_num;
            let last_proportion = rows[0].proportion;
            if (this_target <= last_order_num) return res.send({errCode: 9, message: '设置的订单量必须大于下级！'});
            if(parseInt(this_proportion)<=parseInt(last_proportion)) return res.send({errCode: 9, message: '设置的抽成比例必须大于下级！'});
            //下级
            let nextSql = "select * from level_setting where level=" + (this_level + 1);
            sql.query(nextSql, function (err, rows) {
                if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
                if(rows[0]){
                    if (this_target >= rows[0].order_num) return res.send({errCode: 9, message: '设置的订单量必须小于上级！'});
                    if(parseInt(this_proportion) >= parseInt(rows[0].proportion)) return res.send({errCode: 9, message: '设置的抽成比例必须小于上级！'});
                }
                // 查抽成是否超过100%了，超过返回提示
                let countSql = "select sum(-(-`proportion`)) as count from `level_setting`";
                sql.query(countSql, function (err, rows) {
                    if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
                    let count = 100-(rows[0].count-parseInt(oldData.proportion));
                    if (parseInt(this_proportion) > count) return res.send({errCode: 9, message: '佣金总抽成超过100%，商家要亏本了！'});
                    //执行修改
                    fina();
                })
            })
        })
    }
    //插入数据
    function fina(val){
        let level1 = "update level_setting set level='1',order_num='0',proportion='" + this_proportion +  "' where id=" + id;
        let levelOthers = "update level_setting set level='" + this_level + "',order_num='" + this_target + "',proportion='" + this_proportion +  "' where id=" + id;
        let insertSql = val==1?level1:levelOthers;
        sql.query(insertSql, function (err, rows) {
            if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
            return res.send({errCode:0,message:'修改分销商等级成功'});
        })
    }
});

//删分销商的等级
router.post('/rule/delete', function (req, res) {
    let id = req.body.id;
    let getLevelMaxSql = "select id from level_setting where level = (select max(level) from level_setting)";
    sql.query(getLevelMaxSql, function (err, rows) {
        if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
        if(id!==rows[0].id) return res.send({errCode: 9, message: '请先删除最大级分销商等级!'});
        let deleteSql = "delete from level_setting where id=" + id;
        sql.query(deleteSql, function (err, rows) {
            if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
            res.send({errCode:0,message:"删除成功"});
        })
    })
});

//查等级列表
router.get('/rule', function (req, res, next) {
    let option = "select * from level_setting";
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'查询失败'+err});
        res.send({errCode:0,message:'查询分销商等级成功',result:rows});
    })
});

//查佣金列表明细
router.get('/list', function (req, res, next) {
    let countPageSql = "select count(id) as total from commission";
    let page = req.query.page;
    let option = "select c.`id`,`user`.`email`,c.`money`,`order`.`create_time`,c.`order_id` from `user`,`order`,`commission` as c where `user`.`id`=c.`user_id` and `order`.`id`=c.`order_id` limit ";
    pagination(countPageSql,page,option,function (result) {
        return res.send(result)
    });
});

//搜索
router.get('/search', function (req, res, next) {
   let orderId = req.query.search;
   let option = "select c.`id`,`user`.`email`,c.`money`,`order`.`create_time`,c.`order_id` from `user`,`order`,`commission` as c where `user`.`id`=c.`user_id` and `order`.`id`=c.`order_id` and c.`order_id`="+orderId;
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'查询失败'+err});
        if(rows.length==0){
            return res.send({errCode:9,message:'查无此订单号的信息'});
        }
        res.send({errCode:0,message:'查询订单id成功',result:rows});
    })
});

module.exports = router;
